import java.io.StringReader;

import org.antlr.runtime.ANTLRReaderStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.tree.Tree;

public class DFSPrinter {
	// a main() method for demonstration purposes.
    public static void main(String[] args) throws Exception {
        ANTLRReaderStream input = new ANTLRReaderStream(new StringReader("6*7\nx=(5)\n"));
        TreeExprLexer lexer = new TreeExprLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        TreeExprParser parser = new TreeExprParser(tokens);
        TreeExprParser.prog_return res = parser.prog();
        
        Tree tree = (Tree)res.getTree(); // The root node.
        
        new DFSPrinter().print(tree);
    }
    
	private int indent = 1;

	private String indentString() {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < indent; ++i) {
			sb.append("  ");
		}
		return sb.toString();
	}

	public void print(Tree node) {
		System.out.println("\nPrinting the tree ...");
		dfs_visit(node);
	}

	private void dfs_visit(Tree node) {
		System.out.println(indentString() + printNode(node));
		++indent;
		int count = node.getChildCount();
		for (int i=0;i<count;i++) {
			Tree child = node.getChild(i);
			dfs_visit(child);
		}
		--indent;	  
	}
	
	private String printNode(Tree node) {
		switch (node.getType()) {
		// STATLIST is the root node of the tree. We call it "root" now.
		case TreeExprParser.STATLIST: return "ROOT";
		// INT and ID are integers or identifiers.
		case TreeExprParser.INT: return "INT " + node.toString();
		case TreeExprParser.ID: return "ID " + node.toString();
		// operators can be represented by their tokens
		case TreeExprParser.ASSIGN:
		case TreeExprParser.PLUS:
		case TreeExprParser.MULT: 
		case TreeExprParser.MINUS: return node.toString();
		// all the following tokens cannot be present in the
		// AST because they are dropped through rewrite rules
		// T__13 and T__14 would be '(' and ')'
		case TreeExprParser.NEWLINE:
		case TreeExprParser.WS:
		case TreeExprParser.T__13:
		case TreeExprParser.T__14: throw new RuntimeException();
		case TreeExprParser.EOF:
		default: throw new RuntimeException();
		}
	}
}
